package com.triptogether.utils.gcm.commands;

import java.util.Calendar;

import org.json.JSONObject;

import android.content.Context;
import android.os.Bundle;

import com.triptogether.utils.androidsystem.NotificationsManager;
import com.triptogether.utils.db.DBManager;
import com.triptogether.utils.db.models.User;
import com.triptogether.utils.gcm.GcmCommand;
import com.triptogether.utils.log.Logger;
import com.triptogether.utils.ws.WebServiceUtils;

public class GcmChatCommand implements GcmCommand {

	private final String TAG = Logger.makeLogTag(this.getClass());
	
	private final static String EXTRA_CHAT_MESSAGE = "chatMessage";
	private final static String EXTRA_CHAT_RECEIVED_FROM = "fromUserFacebookId";

	@Override
	public void execute(Context context, Bundle extras) {
		// Get the extras from the gcm message
		String userReceivedFromFacebookId = extras.getString(GcmChatCommand.EXTRA_CHAT_RECEIVED_FROM);
		String chatMessage = extras.getString(GcmChatCommand.EXTRA_CHAT_MESSAGE);

		// try to find the user from the local DB
		DBManager dbManagerInstance = DBManager.getInstance(context);

		// Try to get the user from the local DB
		User findUserByFacebookId = dbManagerInstance.findUserByFacebookId(userReceivedFromFacebookId);

		if (findUserByFacebookId == null) {
			// If there is not user in the Local DB, than call function
			// to get the user from Facebook
			findUserByFacebookId = getUserFromJson(userReceivedFromFacebookId);

			// Than craete the user in the local DB for future use
			dbManagerInstance.createUser(findUserByFacebookId);
		}

		// Create message in the local db
		dbManagerInstance.createMessage(false, findUserByFacebookId, chatMessage,
		        Calendar.getInstance().getTime());

		// Notify the message from user
		NotificationsManager.notifyChatMessage(context, findUserByFacebookId.getUserName(),
		        chatMessage);
	}
	
	/**
	 * Create a User object from the String we get From Facebook Graph API.</br>
	 * The method get a facebook id of a user and get his details from Facebook Graph API by JSON. than create the User object
	 * @param userReceivedFromFacebookId The facebook id of the user we want to get his details
	 * @return {@link User} object with the details filled by the Facebook Graph API.
	 */
	private User getUserFromJson(String userReceivedFromFacebookId) {
		User userToReturn = new User();
		try {
			String responseResult = WebServiceUtils.WsGet(
			        "http://graph.facebook.com/" + userReceivedFromFacebookId).getResponseData();

			// Parse the json result
			JSONObject facebookUserInJson = new JSONObject(responseResult);
			String userName = facebookUserInJson.get("name").toString();

			// Set the details to the user
			userToReturn.setFacebookId(userReceivedFromFacebookId);
			userToReturn.setUserName(userName);
		} catch (Exception e) {
			Logger.LOGE(TAG, e.getMessage(), e);
			return null;
		}

		return userToReturn;
	}

}
